package com.stylefeng.guns.core.util;

import com.google.common.io.Files;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import jodd.io.FileUtil;
import jodd.template.StringTemplateParser;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;

public class SKMKit {

  private final static String references = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?><references xmlns=\"http://sketchup.google.com/schemas/1.0/references\" xmlns:r=\"http://sketchup.google.com/schemas/1.0/references\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://sketchup.google.com/schemas/1.0/references http://sketchup.google.com/schemas/1.0/references.xsd\" />";
  private final static String documentProperties = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?><documentProperties xmlns=\"http://sketchup.google.com/schemas/1.0/documentproperties\" xmlns:dp=\"http://sketchup.google.com/schemas/1.0/documentproperties\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://sketchup.google.com/schemas/1.0/documentproperties http://sketchup.google.com/schemas/1.0/documentproperties.xsd\"><dp:title>${title}</dp:title><dp:description></dp:description><dp:creator></dp:creator><dp:keywords></dp:keywords><dp:lastModifiedBy></dp:lastModifiedBy><dp:revision>0</dp:revision><dp:created>2018-09-18T02:29:03Z</dp:created><dp:modified>2018-09-18T02:29:03Z</dp:modified><dp:thumbnail>doc_thumbnail.${ext}</dp:thumbnail><dp:generator dp:name=\"Material\" dp:version=\"1\" /></documentProperties>";
  private final static String document =
      "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\n"
          + "<materialDocument xmlns=\"http://sketchup.google.com/schemas/sketchup/1.0/material\" \n"
          + "    xmlns:mat=\"http://sketchup.google.com/schemas/sketchup/1.0/material\" \n"
          + "    xmlns:r=\"http://sketchup.google.com/schemas/1.0/references\" \n"
          + "    xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://sketchup.google.com/schemas/sketchup/1.0/material http://sketchup.google.com/schemas/sketchup/1.0/material.xsd\">\n"
          + "    <mat:material name=\"${name}\" type=\"1\" colorRed=\"210\" colorGreen=\"196\" colorBlue=\"177\" colorizeType=\"0\" trans=\"0.5\" useTrans=\"0\" hasTexture=\"1\">\n"
          + "        <mat:texture textureFilename=\"${original_path}\" xScale=\"2.79894590641\" yScale=\"3.937007874016\" avgColor=\"4289840338\">\n"
          + "            <mat:images>\n"
          + "                <mat:image id=\"1\" path=\"${image_name}\" />\n"
          + "            </mat:images>\n"
          + "        </mat:texture>\n"
          + "    </mat:material>\n"
          + "</materialDocument>";

  public static void main(String[] args) throws IOException {
    String imagePath = "D:\\BaiduYunDownload\\1 皮革 布纹 地毯\\布纹\\常用杂项\\1115898279.jpg";
    String dest = "d:\\test.skm";
    generateSkmFileFromImage(imagePath);
  }


  public static File generateSkmFileFromImage(String imagePath) throws IOException {
    File tempDir = Files.createTempDir();
    String imageExtension = Files.getFileExtension(imagePath);
    String nameWithoutExtension = Files.getNameWithoutExtension(imagePath);
    thumbImageFile(imagePath,
        tempDir.getAbsolutePath() + File.separator + "doc_thumbnail." + imageExtension,
        128, 128);
    FileUtil.writeString(new File(tempDir, "references.xml"), references);
    FileUtil.writeString(new File(tempDir, "documentProperties.xml"),
        new StringTemplateParser().parse(documentProperties, macro -> {
          switch (macro) {
            case "title":
              return nameWithoutExtension;
            case "ext":
              return imageExtension;
            default:
              return "";
          }
        }));
    FileUtil.writeString(new File(tempDir, "document.xml"),
        new StringTemplateParser().parse(document, macro -> {
          switch (macro) {
            case "name":
              return nameWithoutExtension;
            case "original_path":
              return imagePath;
            case "image_name":
              return nameWithoutExtension+"."+imageExtension;
            default:
              return "";
          }
        }));
    File to = new File(
        tempDir.getAbsolutePath() + File.separator + "/ref/" + nameWithoutExtension + "."
            + imageExtension);
    Files.createParentDirs(to);
    Files.copy(new File(imagePath), to);
    File destFile = new File(tempDir.getParent(), nameWithoutExtension + ".skm");
    destFile.createNewFile();

    new ZipFiles().zipDirectory(tempDir,destFile.getAbsolutePath());
    return destFile;
  }

  private static void thumbImageFile(String filePath, String dest, int thumbWidth, int thumbHeight)
      throws IOException {
    File file = new File(filePath);
    BufferedImage read = ImageIO.read(file);
    Double widthScale = MathUtil.divide(thumbWidth, read.getWidth());
    Double heightScale = MathUtil
        .divide(thumbHeight, read.getHeight());
    double max = Math.max(widthScale, heightScale);
    Thumbnails.of(file)
        .sourceRegion(Positions.CENTER,
            widthScale > heightScale ? read.getWidth()
                : MathUtil.divide(thumbWidth, max).intValue(),
            widthScale > heightScale ? MathUtil.divide(thumbHeight, max)
                .intValue() : read.getHeight())
        .scale(max)
        .toFile(new File(dest));
  }
}
